<template>
  <view class="message-container">
    <scroll-view 
      scroll-y 
      class="message-list"
      @scrolltolower="loadMore"
      :scroll-with-animation="true"
      :style="{ height: `calc(100vh - ${activeNotice ? '100rpx' : '0'})` }"
    >
      <view 
        v-for="msg in messageList" 
        :key="msg.messageId"
        class="message-card"
        :class="{ 'unread': !msg.isRead }"
      >
        <view @click="gotoDetail(msg.content, msg.messageId)">
          <view class="message-header">
            <uni-icons 
              type="staff-filled" 
              color="#007AFF" 
              size="24"
            />
            <text class="sender">系统管理员</text>
			 <text class="time">{{ msg.sendTime }}</text>

           <!-- <text class="time">{{ formatTime(msg.timestamp) }}</text> -->
          </view>

          <view class="message-content">
            <rich-text :nodes="msg.processedContent"></rich-text>
          </view>

          <view class="message-footer">
            <text 
              :class="`tag ${msg.messageType}`" 
              :style="getTagStyle(msg.messageType)"
            >
              {{ getTagText(msg.messageType) }}
            </text>
            <text v-if="msg.newMessage" class="tag new">最新</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>
<script setup>
	import { ref, onUnmounted, onMounted } from 'vue';
	import { http } from '../../utils/requestUtil';
	import { eventBus } from '../../utils/eventBus';
	
	// 消息类型枚举
	const MESSAGE_TYPE = {
	  URGENT: 'urgent',
	  COMMON: 'common',
	  ANNOUNCE: 'announce',
	  OTHER: 'other'
	};
	
	// 响应式数据
	const messageList = ref([]);
	const activeNotice = ref(null);
	const pageNum = ref(1);
	const pageSize = ref(10);
	const hasMore = ref(true);
	const loading = ref(false);
	const timer = ref(null); // 防抖定时器
	
	// 消息详情跳转 & 状态更新（优化版）
	const gotoDetail = (content, messageId) => {
	 messageList.value.forEach((obj,index) => {
	 	    if (obj.messageId === messageId) {
	 	        obj.isRead = true;
	 			if(messageList.value[index].newMessage == true){
	 				setTimeout(async()=>{
	 					pageNum.value=1
	 					hasMore.value=true
	 					messageList.value=[]
	 					await loadData()
	 					messageList.value[0].isRead=true
	 					await http.get("/privacy/privacy/read?MessageId="+messageList.value[0].messageId)
	 				},500)
	 					
	 			}else{
	 				http.get("/privacy/privacy/read?MessageId="+messageId)
	 			}
	 	    }else{
	 			// pageNum.value=1
	 			// hasMore.value=true
	 			// messageList.value=[]
	 			// loadData()
	 			// http.get("/privacy/privacy/read?MessageId="+messageList.value[0].messageId)
	 		}
	 	});

	uni.navigateTo({
	  url:"/pages/news/newsDetail/newsDetail?msg="+content
	});
	};
	
	// 原生时间格式化（恢复原始逻辑）
	const formatTime = (timestamp) => {
	  if (!timestamp) return '--:--:--';
	  const date = new Date(parseInt(timestamp));
	  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
	};
	
	const pad = (n) => n.toString().padStart(2, '0'); // 补零函数
	
	// 消息类型标签映射（无变化）
	const getTagText = (type) => ({
	  [MESSAGE_TYPE.URGENT]: '紧急',
	  [MESSAGE_TYPE.COMMON]: '普通',
	  [MESSAGE_TYPE.ANNOUNCE]: '通知',
	  [MESSAGE_TYPE.OTHER]: '其他'
	}[type] || '其他');
	
	const getTagStyle = (type) => ({
	  'background-color': {
	    [MESSAGE_TYPE.URGENT]: '#ffe3e3',
	    [MESSAGE_TYPE.COMMON]: '#e3f2fd',
	    [MESSAGE_TYPE.ANNOUNCE]: '#fffdaa'
	  }[type] || '#eee'
	});
	
	// 加载数据（带分页，预处理富文本）
	const loadData = async () => {
	  if (loading.value || !hasMore.value) return;
	  loading.value = true;
	
	  try {
	    const res = await http.get(`/privacy/privacy/message?pageSize=${pageSize.value}&pageNum=${pageNum.value}`);
	    const newItems = res.rows.map(item => ({
	      ...item,
	      processedContent: item.content
	        .replace(/(["'])\/(dev-api|prod-api)/g, (_, quote) => `${quote}https://xit-edu.cn/2503sweepapi`)
	        .replace(/<img[^>]*>/gi, match => match
	          .replace(/style=('|").*?('|")/gi, '')
	          .replace(/width=('|").*?('|")/gi, '')
	          .replace(/height=('|").*?('|")/gi, '')
	        )
	        .replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:10rpx auto;"'),
	      isRead: item.readStatus === '1', // 数据库0/1转布尔值
	      newMessage: false // 初始化新消息标记
	    }));
	
	    messageList.value = [...messageList.value, ...newItems];
	    pageNum.value++;
	    hasMore.value = messageList.value.length < res.total;
	  } catch (error) {
	    uni.showToast({ title: '加载消息失败', icon: 'none' });
	  } finally {
	    loading.value = false;
	  }
	
	  return messageList.value; // 返回最新列表
	};
	
	// 触底加载（带加载提示）
	const loadMore = () => {
	  uni.showLoading({ title: '加载更多消息' });
	  loadData().finally(() => uni.hideLoading());
	};
	
	// 消息接收处理（优化解析逻辑）
	const handleEvent = (data) => {
	  try {
	    const rawData = typeof data.data === 'string' ? JSON.parse(data.data) : data.data;
	    const newMessage = {
	      ...rawData,
	      processedContent: rawData.content
	        .replace(/(["'])\/(dev-api|prod-api)/g, (_, quote) => `${quote}https://xit-edu.cn/2503sweepapi`)
	        .replace(/<img[^>]*>/gi, match => match
	          .replace(/style=('|").*?('|")/gi, '')
	          .replace(/width=('|").*?('|")/gi, '')
	          .replace(/height=('|").*?('|")/gi, '')
	        )
	        .replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:10rpx auto;"'),
	      timestamp: parseInt(rawData.timestamp),
	      isRead: false,
	      newMessage: true, // 标记为新消息
	      messageType: rawData.type || MESSAGE_TYPE.OTHER // 类型兜底
	    };
	
	    messageList.value = [newMessage, ...messageList.value];
	  } catch (error) {
	    console.error('消息解析失败:', error);
	    uni.showToast({ title: '消息格式错误', icon: 'none' });
	  }
	};
	
	// 生命周期钩子（无变化）
	onMounted(() => {
	  eventBus.on('custom-event', handleEvent);
	  loadData();
	});
	
	onUnmounted(() => {
	  eventBus.off('custom-event', handleEvent);
	  clearTimeout(timer.value);
	});
</script>
<style lang=scss>
	/* 公共样式变量 */
	$primary-color: #007AFF;
	$urgent-color: #ff3b30;
	$announce-bg: #fffdaa;
	$tag-padding: 4rpx 16rpx;
	$border-radius: 8rpx;
	
	.message-container {
	  font-family: system-ui;
	  background: #f8f9fa;
	  min-height: 100vh;
	  box-sizing: border-box;
	
	  .message-list {
	    padding: 24rpx;
	    box-sizing: border-box;
	    overflow-y: auto;
	    height: 100vh;
	  }
	
	  .message-card {
	    background: #fff;
	    border-radius: $border-radius;
	    margin-bottom: 24rpx;
	    padding: 24rpx;
	    box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
	
	    &.unread {
	      border-left: 8rpx solid $urgent-color;
	    }
	
	    .message-header {
	      display: flex;
	      align-items: center;
	      margin-bottom: 16rpx;
	
	      .sender {
	        margin-left: 12rpx;
	        font-size: 28rpx;
	        font-weight: 500;
	        color: #333;
	      }
	
	      .time {
	        margin-left: auto;
	        font-size: 24rpx;
	        color: #999;
	      }
	    }
	
	    .message-content {
	      font-size: 28rpx;
	      line-height: 1.6;
	      color: #666;
	      margin: 16rpx 0;
	
	      img {
	        max-width: 100% !important;
	        height: auto;
	        display: block;
	        margin: 16rpx 0;
	        border-radius: $border-radius;
	      }
	    }
	
	    .message-footer {
	      padding-top: 16rpx;
	      border-top: 1rpx solid #f0f0f0;
	      display: flex;
	      align-items: center;
	      gap: 8rpx;
	
	      .tag {
	        font-size: 24rpx;
	        padding: $tag-padding;
	        border-radius: $border-radius;
	        white-space: nowrap;
	
	        &.new {
	          color: #55ff7f;
	          font-weight: 500;
	        }
	      }
	    }
	  }
	}
</style>